﻿#include "controls/imagelabel/cxiimagelabel.h"
#include <QPainter>
#include <QPixmap>
#include <QResizeEvent>
#include <common/logger/logger.h>
#include <imagelabel/cxiimagelabel_p.h>

CxiImageLabel::CxiImageLabel(QWidget* parent)
	: QLabel(parent), d_ptr(new CxiImageLabelPrivate(this))
{
}

CxiImageLabel::~CxiImageLabel() = default;

bool CxiImageLabel::loadFromFile(const QString& path)
{
	Q_D(CxiImageLabel);
	QPixmap pix;
	if (!pix.load(path))
	{
		LOG_ERROR("文件路径加载失败，路径: {}", path.toStdString());
		return false;
	}
	this->setPixmap(pix);
	return true;
}

bool CxiImageLabel::isImageLoaded()
{
	if (pixmap() == nullptr)
		return false;
	return !pixmap()->isNull();
}

void CxiImageLabel::setKeepAspectRatio(bool keepAspectRatio)
{
	Q_D(CxiImageLabel);
	if (d->m_keepAspectRatio == keepAspectRatio) return;
	d->m_keepAspectRatio = keepAspectRatio;
	if (isImageLoaded())
		update();
}

bool CxiImageLabel::hasKeepAspectRatio() const
{
	Q_D(const CxiImageLabel);
	return d->m_keepAspectRatio;
}

void CxiImageLabel::paintEvent(QPaintEvent* event)
{
	Q_D(CxiImageLabel);//如果没有设置按比例缩放，那么使用父类的逻辑
	if (!d->m_keepAspectRatio)
	{
		QLabel::paintEvent(event);
		return;
	}
	if (pixmap() == nullptr || pixmap()->isNull()) return;

	QPainter painter(this);
	painter.setRenderHint(QPainter::SmoothPixmapTransform);
	QSize scaledSize = pixmap()->size().scaled(size(), Qt::KeepAspectRatio);

	QPoint drawPos((width() - scaledSize.width()) / 2,
				   (height() - scaledSize.height()) / 2);

	painter.drawPixmap(drawPos,pixmap()->scaled(scaledSize,
	                   Qt::KeepAspectRatio,Qt::SmoothTransformation));
}
void CxiImageLabel::resizeEvent(QResizeEvent* event)
{
	QLabel::resizeEvent(event);
	Q_D(CxiImageLabel);
	if (d->m_keepAspectRatio && isImageLoaded())
	{
		update();
	}
}